package com.base.app_core.base.impl;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.base.app_core.App;
import com.base.app_core.R;
import com.base.app_core.base.BaseView;
import com.base.app_core.ioc.component.BaseViewComponent;
import com.base.app_core.ioc.module.BaseModule;
import com.base.app_core.model.Paginated;
import com.base.app_core.ui.PermissionsActivity;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.log.F;
import com.gyf.barlibrary.ImmersionBar;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.bugly.crashreport.CrashReport;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

/**
 * Created by xiangheng.song on 2017/2/28.
 */

public abstract class BaseActivity<T extends BasePresenter> extends SwipeBackActivity implements BaseView {

    // 管理运行的所有的activity
    public final static List<WeakReference<FragmentActivity>> mActivities = new LinkedList<WeakReference<FragmentActivity>>();
    public static BaseActivity activity;
    protected ImmersionBar mImmersionBar;

    List<EditText> mEditTexts = new ArrayList<EditText>();

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.head_color);
        mImmersionBar.init();
    }

    protected String[] getPermissions() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        activity = this;
        updateBottom();
    }

    private static final int REQUEST_CODE = 100; // 请求码

    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_CODE, getPermissions());
    }

    public void updateBottom() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideInputSoft();
    }

    protected abstract int getLayoutId();

    protected void setupComponent() {
        F.j(getClass().getCanonicalName());
    }

    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横屏
        requestPermissions();
        if (getLayoutId() != 0) setContentView(getLayoutId());
        setSwipeBackEnable(false);
        mSwipeBackLayout = getSwipeBackLayout();// 设置滑动方向，可设置EDGE_LEFT, EDGE_RIGHT, EDGE_ALL, EDGE_BOTTOM
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
        synchronized (mActivities) {
            mActivities.add(new WeakReference<FragmentActivity>(this));
        }
        initBackButton();
        ButterKnife.bind(this);
        setupComponent();
        attachView();
        initView();
        initData();
        initInputViewAutoClose();
    }


    private void initInputViewAutoClose() {
        if (openInputViewAutoClose()) {
            new MyEditTextCollectTask(this).execute();
        }
    }

    static class MyEditTextCollectTask extends AsyncTask<Void, Void, Void> {

        private WeakReference<BaseActivity> weakAty;

        public MyEditTextCollectTask(BaseActivity activity) {
            weakAty = new WeakReference<>(activity);
        }

        @Override
        protected Void doInBackground(Void... params) {
            if (weakAty == null || weakAty.get() == null) {
                return null;
            }

            BaseActivity activity = weakAty.get();
            if (activity.isFinishing() || activity.isDestroyed()) {
                return null;
            }

            View contentView = XYBAUtils.getContentView(activity);
            if (contentView != null) {
                activity.findEditText(contentView);
            }
            return null;
        }
    }

    private void findEditText(View v) {
        if (v instanceof ViewGroup) {
            ViewGroup parent = (ViewGroup) v;
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = parent.getChildAt(i);
                findEditText(child);
            }
        } else {
            if (v instanceof EditText) {
                mEditTexts.add((EditText) v);
            } else {
                return;
            }
        }
    }

    public void hideInputSoft() {
        if (!XYBAUtils.isEmpty(mEditTexts)) {
            for (int i = 0; i < mEditTexts.size(); i++) {
                EditText editText = mEditTexts.get(i);
                hideInputSoft(editText);
            }
        }
    }

    protected void hideInputSoft(EditText editText) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive(editText)) {
            inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 清空所有的焦点
     */
    public static void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
        Field f = null;
        Object obj_get = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                }
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        F.j(BaseActivity.class.getSimpleName() + "====>" + "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext() + " dest_context=" + destContext);
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    private void requestPermissions() {
        if (null == getPermissions())
            return;
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(getPermissions())
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            Log.d("jason", permission.name + " is granted.");
                            doGrantedPermission(permission);
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            donotGrantedPermission(permission);
                            Log.d("jason", permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Log.d("jason", permission.name + " is denied.");
                        }
                    }
                });
    }

    protected void donotGrantedPermission(Permission permission) {
        showToast("很遗憾");
        this.finish();
    }

    protected void doGrantedPermission(Permission permission) {
    }

    /**
     * 返回按钮id统一为back,如果有id为back的View,就注册返回事件
     */
    private void initBackButton() {
    }

    protected void initView() {
        setToolBar("注册");
        try {
            InitQinRuShi();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void initData() {
        if (needShowLoading()) {
            dismissView(getmErrorView());
            showView(getLoadingView());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        synchronized (mActivities) {
            mActivities.remove(this);
        }
        if (mImmersionBar != null) {
            ImmersionBar.with(this).destroy();
            mImmersionBar = null;
        }
        mEditTexts.clear();
        mEditTexts = null;
        if (mPresenter != null) {
            mPresenter.attachView(null);
        }
    }

//    public void killAll() {
//        // 复制了一份mActivities 集合Å
//        List<FragmentActivity> copy;
//        synchronized (mActivities) {
//            copy = new LinkedList<>(mActivities);
//        }
//        for (FragmentActivity activity : copy) {
//            activity.finish();
//        }
//        // 杀死当前的进程
//        android.os.Process.killProcess(android.os.Process.myPid());
//    }

    //下面的用于侧滑关闭Activity
    public void touchFinish() {
        super.finish();
        //overridePendingTransition(R.anim.alpha_enter, R.anim.alpha_exit);
    }

    @Inject
    public T mPresenter;

    protected void attachView() {
        if (mPresenter != null)
            mPresenter.attachView(this);
    }

    protected BaseViewComponent getBaseViewComponent() {
        return App.getApp().getAppComponent().plus(getActivityModule());
    }

    protected BaseModule getActivityModule() {
        return new BaseModule(this);
    }

    private View mLoadingView = null;

    protected View getLoadingView() {
        if (null == mLoadingView) {
            mLoadingView = LayoutInflater.from(this).inflate(R.layout.basefragment_state_loading, null);
        }
        return mLoadingView;
    }

    private View mErrorView = null;

    protected View getmErrorView() {
        if (null == mErrorView) {
            mErrorView = LayoutInflater.from(this).inflate(R.layout.basefragment_state_error, null);
            LinearLayout ll_error_refresh = (LinearLayout) mErrorView.findViewById(R.id.ll_error_refresh);
            ll_error_refresh.setVisibility(View.VISIBLE);
            ll_error_refresh.setBackgroundColor(Color.WHITE);
            ll_error_refresh.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initData();
                }
            });
        }
        return mErrorView;
    }

    public boolean needShowLoading() {
        return false;
    }

    protected void showView(View view) {
        if (isFinishing()) {
            return;
        }
        if (view != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            ViewGroup rootView = getRootView(this);
            if (rootView == null) {
                return;
            }

            if (rootView.indexOfChild(view) == -1)
                rootView.addView(view, params);
        }
    }

    protected void dismissView(View view) {
        if (isFinishing()) {
            return;
        }

        ViewGroup rootView = getRootView(this);
        if (rootView == null) {
            return;
        }

        try {
            if (null != view && rootView.indexOfChild(view) != -1)
                rootView.removeView(view);
        } catch (Exception e) {
            e.printStackTrace();
            CrashReport.postCatchedException(e);
        }
    }

    @Override
    public void setState(int state) {
        if (state == AppConstants.STATE_SUCCESS) {
            dismissView(getmErrorView());
            dismissView(getLoadingView());
        }
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        dismissProgress();
    }

    /**
     * 沉浸式的功能区
     */
    public boolean openQinRuShiUi() {//默认页面开启沉浸式，如果不需要开启则重写返回false
        return true;
    }

    /**
     * 是否设置Edittext关闭窗口自动关闭
     *
     * @return
     */
    public boolean openInputViewAutoClose() {
        return true;
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public void InitQinRuShi() {
        if (openQinRuShiUi() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ////4.4及以上版本开启
//                setTranslucentStatus(true);
//            if(null!=toolbar)ImmersionBar.with(this).titleBar(R.id.toolbar).init();
//            else
            initImmersionBar();
        }
    }

    /**
     * 子类可以直接用
     *
     * @param title
     */
    private Toolbar toolbar;
    private TextView mheadcentercontent;

    protected void setToolBar(String... title) {
        if (null == toolbar)
            toolbar = (Toolbar) findViewById(R.id.toolbar);
//        if(null!=toolbar){
//            toolbar.setTitle("");
//            setSupportActionBar(toolbar);
//            getSupportActionBar().setDisplayHomeAsUpEnabled(false);//显示toolbar的返回按钮
//            getSupportActionBar().setDisplayShowHomeEnabled(true);
//            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    onBackPressed();
//                }
//            });
//        }
        mheadcentercontent = (TextView) findViewById(R.id.center_title);
        if (mheadcentercontent != null)
            mheadcentercontent.setText(title[0]);

        ImageView close_category_list = (ImageView) findViewById(R.id.close_category_list);
        if (null != close_category_list) {
            close_category_list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
            if (title.length > 1 && title[1].equals(AppConstants.Const.UNDISCLOSE)) {
                close_category_list.setVisibility(View.GONE);
            }
        }

        TextView center_title = (TextView) findViewById(R.id.center_title);
        if (null != center_title)
            center_title.setText(title[0]);

    }

    public void showToast(String content) {
        Toast toast = Toast.makeText(this, content, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public void showProgress() {//显示进度提醒
        if (null == mLoadProess) {
            mLoadProess = LayoutInflater.from(this).inflate(R.layout.loading_view_layout, null);
        }

        if (mLoadProess != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            if (getRootView(this).indexOfChild(mLoadProess) == -1)
                getRootView(this).addView(mLoadProess, params);
        }
    }

    private View mLoadProess = null;

    protected ViewGroup getRootView(Activity context) {
        return (ViewGroup) ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);
    }

    //    public void showProgress(){//显示进度提醒
//        if(null==mLoadProess){
//            mLoadProess= LayoutInflater.from(this).inflate(R.layout.loading_view_layout,null);
//        }
//        if(mLoadProess!=null){
//            FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//            if(getRootView(this).indexOfChild(mLoadProess)==-1)
//            getRootView(this).addView(mLoadProess,params);
//        }
//    }

    protected void dismissProgress() {//关闭进度条
        if (null != mLoadProess && getRootView(this).indexOfChild(mLoadProess) != -1)
            getRootView(this).removeView(mLoadProess);
    }

    @Override
    public void notifyError(String errorCode, String content) {
        showToast(content);
        dismissProgress();
        if (needShowLoading()) {
            dismissView(getLoadingView());
            showView(getmErrorView());
        }
    }

    @Override
    public void onLoginSuccess() {
    }

    protected View getEmptyView(RecyclerView view, String maintile, String subtitle) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.view_empty_layout, null);
        TextView textmain = (TextView) inflate.findViewById(R.id.maintitile);
        TextView textsub = (TextView) inflate.findViewById(R.id.subtitile);
        textmain.setText(maintile);
        textsub.setText(subtitle);
        inflate.setVisibility(View.GONE);
        ((ViewGroup) view.getParent()).addView(inflate, -1);
        return inflate;
    }

    protected View getEmptyView(ViewGroup view, String maintile, String subtitle) {
        View view1 = LayoutInflater.from(this).inflate(R.layout.view_empty_layout, null);
        TextView textmain = (TextView) view1.findViewById(R.id.maintitile);
        TextView textsub = (TextView) view1.findViewById(R.id.subtitile);
        textmain.setText(maintile);
        textsub.setText(subtitle);
        view.addView(view1, -1);
        return view1;
    }

    protected View getEmptyView(ListView view, String maintile, String subtitle) {
        View view1 = LayoutInflater.from(this).inflate(R.layout.view_empty_layout, null);
        TextView textmain = (TextView) view1.findViewById(R.id.maintitile);
        TextView textsub = (TextView) view1.findViewById(R.id.subtitile);
        textmain.setText(maintile);
        textsub.setText(subtitle);
        ((ViewGroup) view.getParent()).addView(view1, -1);
        return view1;
    }

}
